/* global window */
import modelExtend from 'dva-model-extend'
import * as auditFailedOrderService from './services/auditFailedOrder'
import {pageModel} from 'utils/model'

const {query} = auditFailedOrderService

export default modelExtend(pageModel, {
  namespace: 'auditFailedOrder',

  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
    selectRecord: {},
    disable: false,
  },

  subscriptions: {
    setup ({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/auditFailedOrder') {
          const payload = location.query || {current: 1, size: 10}
          dispatch({
            type: 'query',
            payload,
          })
        }
      })
    },
  },

  effects: {

    * query ({payload = {}}, {call, put}) {
      const response = yield call(query, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.records,
            pagination: {
              current: Number(payload.current) || 1,
              pageSize: Number(payload.size) || 10,
              total: data.total,
            },
          },
        })
      }
    },

    * delete ({payload}, {call, put, select}) {
      const data = yield call(auditFailedOrderService.remove, {id: payload})
      const {selectedRowKeys} = yield select(_ => _.auditFailedOrder)
      if (data.code === 0) {
        yield put({type: 'updateState', payload: {selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload)}})
      } else {
        throw data
      }
    },



    * multiDelete ({payload}, {call, put}) {
      const data = yield call(auditFailedOrderService.batchDelete, payload)
      if (data.code === 0) {
        yield put({type: 'updateState', payload: {selectedRowKeys: []}})
      } else {
        throw data
      }
    },


    * create ({payload}, {call, put}) {
      const data = yield call(auditFailedOrderService.create, payload)
      if (data.code === 0) {
        yield put({type: 'hideModal'})
      } else {
        throw data
      }
    },

    * update ({payload}, {select, call, put}) {
      const id = yield select(({auditFailedOrder}) => {
        if (payload.id) {
          return payload.id
        }
        return auditFailedOrder.currentItem.id
      })

      const newObj = {...payload, id}
      const data = yield call(auditFailedOrderService.update, newObj)
      if (data.code === 0) {
        yield put({type: 'hideModal', payload: {
            selectedRowKeys: [],
            selectRecord: {},
            resetRoleModalVisible: false,
          }})
      } else {
        throw data
      }
    },

  },

  reducers: {

    showModal (state, {payload}) {
      return {...state, ...payload, modalVisible: true}
    },


    hideModal (state) {
      return {...state, modalVisible: false}
    },



  },
})
